//
//  SaveObject.m
//  CheckmeRing
//
//  Created by 董鹏 on 2022/2/23.
//

#import "SaveObject.h"

@implementation SaveObject

+ (NSString *)saveToLocal:(NSArray *)data {
    return [[[self alloc] init] creatCSV:data];
}

- (NSString *)creatCSV:(NSArray *)data{
    NSString *basePath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    // CheckmeRing_yyyyMMddHHmmss
    NSDictionary *dict = data.firstObject;
    NSString *filePath = [basePath stringByAppendingPathComponent:[NSString stringWithFormat:@"CheckmeRing_%@.csv", [self formatDate:[dict[@"timeStamp"] intValue] format:@"yyyyMMddHHmmss"]]];
    NSLog(@"filePath = %@", filePath);
    
    [self createFile:filePath];
    [self writeCSV:filePath historyData:data];
    return filePath;
}


- (void)createFile:(NSString *)fileName {
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager removeItemAtPath:fileName error:nil];

    if (![fileManager createFileAtPath:fileName contents:nil attributes:nil]) {
        NSLog(@"不能创建文件");
    }
    
}

- (void)writeCSV:(NSString *)fileName
     historyData:(NSArray *)data {
    
    NSFileHandle* fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:fileName];
    //将节点调到文件末尾
    [fileHandle seekToEndOfFile];
    
    NSString *title = [NSString stringWithFormat:@"Time,SpO2,Pulse Rate,Motion\n"];
    NSData *titleData = [title dataUsingEncoding:NSUTF8StringEncoding];
    [fileHandle writeData:titleData];
    
    
    for(int i = 0; i < data.count; i++){
        NSDictionary *model = data[i];
        
        NSString *str = [NSString stringWithFormat:@"%@,%d,%d,%d\n", [self formatDate:[model[@"timeStamp"] intValue] format:@"HH:mm:ss MMM dd yyyy"], [model[@"spo2"] intValue], [model[@"hr"] intValue], [model[@"vector"] intValue]];
        NSData *stringData = [str dataUsingEncoding:NSUTF8StringEncoding];
        //追加写入数据
        [fileHandle writeData:stringData];
    }

    [fileHandle closeFile];

}

- (NSString *)formatDate:(int)timeStamp
                  format:(NSString *)format {
    
    NSTimeInterval time = timeStamp;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:time];
    // 时间格式
    NSDateFormatter *dataformatter = [[NSDateFormatter alloc] init];
    dataformatter.dateFormat = format;
    NSString *result = [dataformatter stringFromDate:date];
    
    return result;
}

@end
